# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time        : 2021/10/21 14:29
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : convolve2d.py
@Version     : Version 1.0.0
@Description : TODO
@Created By  : PyCharm
"""
from scipy.signal import convolve2d
from skimage.io import imread
import numpy as np
from DIP_experiment_5.util import contrast_show

# 以灰度图形式读入图像
font_path = "C:/Windows/Fonts/simhei.ttf"
im_path = "../experiment_fig/chess.jpg"
im = imread(im_path, as_gray=True)

# 第一组梯度算子
x1_ker = np.array([[-1, 0, 1]])
# 第二组梯度算子
x2_ker = np.array([[-1, 1]])
# 边缘检测
for ker in [x1_ker, x2_ker]:
    x_im = convolve2d(im, ker, mode="same")
    x_im = np.where(x_im == 0, 1e-8, x_im)  # 由于除法分母不能为0，故用1e-8近似表示
    y_im = convolve2d(im, ker.T, mode="same")
    im_mag = np.sqrt(x_im ** 2 + y_im ** 2)
    im_ang = np.arctan(y_im / x_im)
    im_dict = {"水平边缘": y_im, "垂直边缘": x_im, "梯度大小": im_mag, "梯度方向": im_ang}
    contrast_show(im_dict, (2, 2), hspace=0.4, font=font_path)

# 第三组梯度算子
laplace_ker = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edge = convolve2d(im, laplace_ker, mode="same")
im_dict = {"原始图像": im, "原始边缘": edge}
contrast_show(im_dict, (1, 2), font=font_path)
